'use strict'
const compile = require('./compile')
class Packet {
  constructor () {}
  toBuffer (msg) {
    var bodybuf = new Buffer(compile.serialize(msg)
      .concat('\0'))
    var headbuf = new Buffer(12)
    var buf = Buffer.concat([headbuf, bodybuf], bodybuf.length + headbuf.length)
    buf.writeInt32LE(buf.length - 4, 0)
    buf.writeInt32LE(buf.length - 4, 4)
    buf.writeInt16LE(689, 8)
    buf.writeInt16LE(0, 10)
    return buf
  }
  toJson (data) {
    try {
      if (data) {
        let buffer = new Buffer(data, 'hex')
        // let packetLength = buffer.readInt32LE(0)
        // let packetLength2 = buffer.readInt32LE(4)
        // let packetType = buffer.readInt16LE(8)
        // let encrypt = buffer.readInt8(10)
        // let reserved = buffer.readInt8(11)
        let body = buffer.toString('utf8', 12)
        return compile.deserialize(body)
      }
    } catch (e) {
      return null
    } finally {

    }
  }
}
module.exports = new Packet()
